import { Component, OnInit } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { catchError, debounceTime, switchMap, map } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { ServiceResult } from '@core/constant';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { UserService } from '../../../../service/user/user.service';
import { GroupService } from '../../../../service/group/group.service';

@Component({
  selector: 'app-group-member-modal',
  templateUrl: './group-member-modal.component.html',
  styles  : [ `
    .loading-icon {
      margin-right: 8px;
    }
  ` ]
})
export class GroupMemberModalComponent implements OnInit {
    groupId = null;
    searchChange$ = new BehaviorSubject('');
    optionList = [];
    selectedUser;
    isLoading = false;
    private subject = new Subject();

    constructor(
        private modal: NzModalRef,        
        public msg: NzMessageService, 
        private modalSrv: ModalHelper,  
        private userService: UserService,  
        private groupService: GroupService,    
        private http: _HttpClient
    ) {

    }

    ngOnInit() {        
        const getRandomNameList = (name: string) =>             
            this.http.get(`${this.userService.list()}?name=${name}&username=${name}`).pipe(
                map((res: any) => res.data.rows)
            ).pipe(
                map((list: any) => {                     
                    return list.map(item => {
                        let userinfo = JSON.parse(item.userId);
                        return {label: `${userinfo.name}`, value: `${userinfo.id}`}
                    });
                }
            ));
        const optionList$: Observable<any[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(getRandomNameList));
        optionList$.subscribe(data => {
            this.optionList = data;
            this.isLoading = false;
        });
        // 获取角色组成员
        this.loadMember();
    }

    loadMember() {
        this.groupService.getGroupMember2(this.groupId).pipe(
            catchError(err => {                             
                return of(err);
            })
        ).subscribe(data => {
            if (data.status === 200) {
                this.selectedUser = [];                
                for (let i = 0; i < data.data.members.length; i++) {
                    this.selectedUser.push(data.data.members[i].id);
                    if (this.optionList.length === 0) {
                        this.optionList.push({label: data.data.members[i].name, value: data.data.members[i].id});
                    } else {
                        let index = this.optionList.findIndex((v, i, o) => {
                            return v.value == data.data.members[i].id
                        });
                        if (index < 0) {
                            this.optionList.push({label: data.data.members[i].name, value: data.data.members[i].id});
                        }
                    }
                }               
            } 
        })
    }

    onSearch(value: string): void {
        this.isLoading = true;
        this.searchChange$.next(value);
    }

    close() {
        this.modal.close(true);
        this.modal.destroy();
    }

    save() {        
        this.subject.next(this.selectedUser.toString());
        this.close();        
    }

    getSubject() {
        return this.subject;
    }

}